package com.sann.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sann.common.utils.R;
import com.sann.common.utils.ResultCode;
import com.sann.eduservice.client.VodClient;
import com.sann.eduservice.entity.chapter.Video;
import com.sann.eduservice.mapper.VideoMapper;
import com.sann.eduservice.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sann.servicebase.handler.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author zjw
 * @since 2021-04-17
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;

    // 根据课程Id删除小节，同时删除课程下所有的阿里云视频文件
    @Override
    public void removeByCourseId(String courseId) {
        // 1 批量删除小节对应在阿里云上视频
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", courseId);// where 条件
        videoQueryWrapper.select("video_source_id");// 查询的字段
        List<Video> videos = this.baseMapper.selectList(videoQueryWrapper);

        // List<Video> 变成 List<String>
        List<String> videoIds = new ArrayList<>();
        for (Video video : videos) {
            // 存在video_source_id阿里云视频资源id
            if (Objects.nonNull(video) && Objects.nonNull(video.getVideoSourceId())) {
                videoIds.add(video.getVideoSourceId());
            }
        }

        if (!videoIds.isEmpty()) {
            // 有阿里云视频存在，需要删除
            vodClient.batchDeleteVideo(videoIds);
        }

        // 2 批量删除小节
        QueryWrapper<Video> wrapper = new QueryWrapper();
        wrapper.eq("course_id", courseId);
        this.baseMapper.delete(wrapper);
    }

    // 根据小节Id删除小节，同时删除小节里面的视频
    @Override
    public boolean deleteVideoById(String videoId) {
        // 根据videoId小节Id查询阿里云视频id
        Video video = this.baseMapper.selectById(videoId);
        String videoSourceId = video.getVideoSourceId();

        if (!StringUtils.isEmpty(videoSourceId)) {
            // videoSourceId阿里云视频Id不为空，执行删除视频
            R r = vodClient.deleteAliVideo(videoSourceId);
            if (!r.getSuccess()) {
                throw new GuliException(ResultCode.ERROR, r.getMsg());
            }
        }

        // 根据videoId小节Id删除小节
        int count = this.baseMapper.deleteById(videoId);
        return count>0;
    }
}
